﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.DataSourcesGDB;

namespace ArgGisUI
{
    public class LayerImporterContainer
    {
        private string accessFileName;
        private string[] layerNames;
        public LayerImporterContainer(string accessFileName, string[] layerNames)
        {
            this.accessFileName=accessFileName;
            this.layerNames = layerNames;
            this.autoEvent=new AutoResetEvent(false);
        }
        private List<ManualResetEvent> importDoneEvents= new List<ManualResetEvent>();
        private AutoResetEvent autoEvent;
        public void Import()
        {
             IFeatureWorkspace workspace = CreateAccessWorkspace() as IFeatureWorkspace;
              for (int i = 0; i < layerNames.Length; i++)
            {
                string layerName = layerNames[i];
                ITable table = workspace.OpenTable(layerName);
                int rowCount = table.RowCount(null);
                if (rowCount > 0)
                {
                    LayerImporter layerImporter= new LayerImporter(autoEvent,accessFileName,new ImportLayerInfo{LayerName=layerName});
                    importDoneEvents.Add(layerImporter.DoneEvent);
                        Thread thread = new Thread(new ThreadStart(layerImporter.Import));
                        thread.SetApartmentState(ApartmentState.STA);
                        thread.Start();
                  

                }
            }
            autoEvent.Set();
            foreach (var doneEvent in importDoneEvents)
            {
                doneEvent.WaitOne();
            }
            //WaitHandle.WaitAll(importDoneEvents.ToArray());
        }
        private IWorkspace CreateAccessWorkspace()
        {
            IPropertySet propertySet = new PropertySetClass();
            propertySet.SetProperty("DATABASE", accessFileName);

            IWorkspaceFactory2 workspaceFactory = new AccessWorkspaceFactoryClass();
            return workspaceFactory.Open(propertySet, 0);
        }

    }
}
